package com.woniuxy.java102vuecli.controller;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.core.codec.Base64;
import com.woniuxy.java102vuecli.entity.VerifyCodeVO;
import com.woniuxy.java102vuecli.util.VerifyCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author author
 * @Create 2023-09-27 10:54
 */
@Slf4j
@RestController
public class VeriyCodeController {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/verifycode")
    public ResponseResult<VerifyCodeVO> createVerifyCode() throws IOException {
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(100, 50,4,5);
        String verifycode = captcha.getCode();
        log.info("verifycode={}",verifycode );
        //验证码存入redis,uui作为key
        String uuid= UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(uuid,verifycode,10, TimeUnit.MINUTES);
        //如何保存，用户提交表单，比较验证码
        try (ByteArrayOutputStream outputStream=new ByteArrayOutputStream()){
            captcha.write(outputStream);
            String verifycodesrc = Base64.encode(outputStream.toByteArray());
            log.info("base64={}", verifycodesrc);
            log.info("base64={}", ((AbstractCaptcha)captcha).getImageBase64());
            log.info("base64={}", ((AbstractCaptcha)captcha).getImageBase64Data());
            log.info("base64={}", verifycodesrc);

            return new ResponseResult<>(200,"ok",new VerifyCodeVO(verifycodesrc,uuid));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @RequestMapping("/verifycode1")
    public void createVerifyCode1(HttpServletResponse response, HttpSession session) throws IOException {
        VerifyCode verifyCode=new VerifyCode();
        //保存
//        session.setAttribute("session_verifycode",verifyCode);
        BufferedImage image=verifyCode.getImage();
        log.info("验证码{}",verifyCode.getText());
//        VerifyCode.output(image, response.getOutputStream());
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        VerifyCode.output(image, outputStream);
        String encode = Base64.encode(outputStream.toByteArray());
        System.out.println(encode);
    }
}
